/**
 * Created by yunpeng on 2015/3/26.
 */
angular.module('starter.orderControllers', ['ui.router'])
    .config(function($stateProvider, $urlRouterProvider){
        $stateProvider
            .state('tab.orderDetail' ,{
                url:'/myOrders/orderdetail',
                templateUrl:'view/order/order-detail.html',
                controller:'OrderDetailCtrl'
                ,access: { requiredLogin: true }
            })
            .state('tab.orderComment' ,{
                url:'/myOrders/ordercomment',
                templateUrl:'view/order/order-comment.html',
                controller:'OrderCommentCtrl'
                ,access: { requiredLogin: true }
            })
            .state('tab.orderCars' ,{
                url:'/myOrders/ordercars'
                ,templateUrl:'view/order/order-cars.html'
                ,controller:'OrderCarsCtrl'
                ,access: { requiredLogin: true }
            })
    })
    .filter('dateFormat' ,function(){
        return function(input){
            if(typeof input == 'string'){
                return input.substring(0 ,10);
            }
        }
    })
    .filter('orderState' ,function(){
        return function(input){
            switch (input){
                case 5:return '已取消';
                case 2:return '已接受';
                case 3:return '已评价';
            }
        }
    })
    .controller('MyOrderCtrl',function($scope,$rootScope,$state,$http ,OrderService){
        /*$scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});//初始化ISCroll
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);*/
        $('#order-wrapper').css('min-height',$(window).height()-135+'px');


        $scope.switch = OrderService.switch;
        var order = $scope.orders = OrderService.orders();//重新打开我的订单页面时，从OrderService初始化数据
        if($rootScope.refreshOrder){
            order[0] = order[1] = [];
            $rootScope.refreshOrder = false;
        }
        /*if(order[$scope.switch].length == 0){

            loadOrder();
        }else{
            setTimeout(function(){
                refreshScroll();
            },300);
        }*/

        pull($scope,"wrapper",function(pull){
            if(OrderService.busy)return;
            if('pullDown'==pull) {//下拉刷新
                loadOrder();
            }else{//上拉加载更多
                moreOrder();
            }
        });

        //切换订单tab选项
        $scope.switchOrders = function(idx){
            //$scope.myScroll.scrollTo(0, - $scope.pullDownOffset,0);
            $scope.switch = OrderService.switch = idx;
            $('.noorder').hide();
            if(idx==0){
                $('.order1').hide();
                $('.order0').show();
            }else{
                $('.order0').hide();
                $('.order1').show();
            }
            refreshScroll();
            if(order[$scope.switch].length==0){
                loadOrder();
            }
        }
        $scope.switchOrders($scope.switch);

        //跳转到订单详情页
        $scope.goDetail = function(idx){
            OrderService.setIdx(idx);
            $state.go('tab.orderDetail');
            //$scope.count++;
        }


        var config = {
            timeout:8000
        }
        $scope.noOrders = OrderService.noOrders;
        $scope.noMore = false;
        function loadOrder(){
            OrderService.busy = true;

            var params = OrderService.param();
            var page = params.page;//如果加载失败，恢复之前的页数
            params.page = 1;
            $http.post('/users/myorders' ,params ,config)
                .success(function(data,status) {
                    if(data.err){
                        params.page = page;
                    }else{
                        if(data.total == 0){
                            //$scope.noOrders[$scope.switch] = true;
                            $('.noorder').show();
                        }else{
                            //$scope.noOrders[$scope.switch] = false;
                            $('.noorder').hide();
                        }
                        truncateOrder(data.rows);
                        OrderService.putOrder(data );
                        //$scope.$apply();

                        refreshScroll();
                    }
                    OrderService.busy = false;

                })
                .error(function (data,status) {
                    params.page = page;
                    OrderService.busy = false;
                });

        }
        function moreOrder(){
            var status = OrderService.status();
            /*if(status.total == status.length){//所有数据都已被加载
             return;
             }*/
            if(!$scope.orders[$scope.switch].length){//如果没有数据，加载第一页
                loadOrder();
                return;
            }
            var params = OrderService.param();
            params.page += 1;
            OrderService.busy = true;
            $http.post('/users/myorders' ,params ,config)
                .success(function(data) {
                    if(data.err){
                        params.page -= 1;
                    }else{
                        if(data.rows.length == 0){
                            //var wHeight = screen.clientHeight;
                            //document.getElementById('noMore').style.top = wHeight - 100 + 'px';
                            document.getElementById('noMore').style.display = 'block';
                            setTimeout(function () {
                                document.getElementById('noMore').style.display = 'none';
                            } ,2000)
                        }
                        truncateOrder(data.rows);
                        OrderService.appendOrder(data );
                        //$scope.$apply();
                    }
                    OrderService.busy = false;

                    refreshScroll();

                })
                .error(function (data,status) {//alert(status);
                    params.page -= 1;
                    OrderService.busy = false;

                });
        }

        function truncateOrder(rows){
            var rs = rows;
            for(var x in rs){
                var i = rs[x];
                if(i.type == 1){
                    var carnums = i.carnum.split(',');
                    i.carnums = carnums;
                    var nums = i.num.split(',');
                    var totalnum = 0;
                    for(var xx in nums){
                        nums[xx] = Number(nums[xx]);
                        totalnum += nums[xx];
                    }
                    i.nums = nums;
                    i.total = totalnum;
                    i.note = '本次共运送 '+carnums.length+'种型号共 '+totalnum+'辆车';
                }else if(i.type == 2){
                    i.nums =  i.carnum.split(',');
                    i.nums[0] = Number(i.nums[0])
                    i.nums[1] = Number(i.nums[1])
                    i.note = '本次共运送 ';
                    if(i.nums[0]){
                        i.note += '小板'+i.nums[0] + '板 ';
                    }
                    if(i.nums[1]){
                        i.note += '大板'+i.nums[1] + '板';
                    }
                }
            }

        }

        function refreshScroll(){
            setTimeout(function(){//因为有冲突等会执行scope.$apply();
                //$scope.$apply();
                if($scope.myScroll){
                    $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                }
            },300);
        }
    })
    .controller('OrderDetailCtrl' ,function($scope ,$state ,$http ,OrderService){
        //初始化内容区的弹动
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        var order = OrderService.get();
        $http.post('/users/orderdetail' ,{id:order.id})
            .success(function(data){
                if(data.err){

                }else{
                    /*var oldDetail = OrderService.orderDetail;
                    if(oldDetail && data.id != oldDetail.id){
                        OrderService.comment = null;//清空之前做的评论数据
                    }*/
                    OrderService.set(data);
                    order = OrderService.orderDetail = $scope.order = data;

                    setTimeout(function(){
                        $scope.myScroll.refresh();
                    },600);
                }
            })
            .error(function(data){

            })

        var busy = false;
        $scope.cancel = function(){
            if(busy || order.status != 2)return;
            busy = true;
            if(!confirm('确定取消该订单吗？')){
                setTimeout(function(){busy=false;},200)
                return;
            }
            $http.post('/users/cancelorder' ,{id:$scope.order.id})
                .success(function(data){
                    if(data.err){
                        alert('网络连接出错，请稍候再试')
                    }else{
                        $rootScope.refreshOrder = true;
                        order.status = 5;
                        alert('订单取消成功！')
                    }
                    busy = false;
                })
                .error(function(data){
                    busy = false;
                })
        }

        $scope.go = function(state){
            $state.go(state);
        }
        $scope.goComment = function(){
            if(order.status == 5)return;
            $state.go('tab.orderComment');
        }

    })
    .controller('OrderCarsCtrl' ,function($scope ,$state ,OrderService){
        //初始化内容区的弹动
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        var order = $scope.order = OrderService.orderDetail;
        var cars = $scope.cars = order.cars;
        if(order.type==1){
            $scope.orderCount = order.total + '辆车';
        }else{
            $scope.types = [];
            var cc = '';
            if(order.carnums[0]){
                cc += order.carnums[0]+'个小板';
                $scope.types.push({type:'小板',num:order.carnums[0]})
            }
            if(order.carnums[1]){
                cc += order.carnums[1]+'个大板';
                $scope.types.push({type:'大板',num:order.carnums[1]})
            }
            $scope.orderCount = cc;
        }

        setTimeout(function(){
            $scope.myScroll.refresh();
        },600);
    })
    .controller('OrderCommentCtrl' ,function($scope ,$rootScope,$state ,$http ,OrderService){
        //初始化内容区的弹动
        $scope.myScroll = new IScroll('#wrapper', { mouseWheel: true  ,click:true});
        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        var order = OrderService.orderDetail;
        var carrier = $scope.carrier = OrderService.orderDetail.carrier;

        $scope.flag = order.status == 3;
        if($scope.flag){
            $scope.comment = order.comment;
            document.getElementById('commentText').disabled = true;
        }else{
            var comment = OrderService.comment;
            if(comment && comment.inforid == order.id){
                $scope.comment = comment;
            }else{
                OrderService.comment = $scope.comment = {
                    attitude:0
                    ,care:0
                    ,corresponds:0
                    ,evaluation:''
                    ,inforid:order.id
                    ,userid:order.user.id
                    ,carrierid:carrier.id
                }
            };
        }
        $scope.authImg = (carrier.authstate == 0 ? 'icon-icon-19' : 'icon-icon-18');
        $scope.authText = (carrier.authstate == 0 ? '未认证' : '已认证');
        $scope.postText = $scope.flag?'已 评 价':'评 价';


        //评价打分
        $scope.graderArray = [1,2,3,4,5];
        $scope.grade = function(t ,idx){
            if($scope.flag)return;
            $scope.comment[t] = idx +1;
        }
        setTimeout(function(){
            $scope.myScroll.refresh();
        },600);
        //
        $scope.go = function(state){
            $state.go(state);
        }
        //提交评论
        $scope.post = function(){
            if($scope.flag)return;
            if(!($scope.comment.attitude && $scope.comment.care && $scope.comment.corresponds && $scope.comment.evaluation)){
                alert('请输入完整评价');
                return;
            }
            $http.post('/users/comment' ,{commentJSON:JSON.stringify($scope.comment)})
                .success(function(data){
                    if(data.err){
                        alert('评价失败，请稍候再试！')
                    }else{
                        $rootScope.refreshOrder = true;
                        $scope.flag = true;
                        OrderService.orderDetail.status = 3;
                        OrderService.orderDetail.comment = $scope.comment;
                        document.getElementById('commentText').disabled = true;
                        alert('评价成功！')
                    }
                })
                .error(function(data){

                })
        }
    });